<!-- 个人考勤 -->
<template>
  <ContainerLayoutV2 ref="containerLayoutRef" class="attendance-personal">
    <template #form>
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <TimeSlotDatePicker label="月份" v-model="queryForm.date" dateType="month" styleWidth="120px" :shortcuts="[]" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template #tables>
      <div class="table-container">
        <div class="table-1">
          <div class="table-title">{{ currentMonth.getMonth() + 1 }}月份请假类型（天）</div>
          <el-table :data="tableData1" v-loading="loading" scrollbar-always-on style="width: 100%" border header-cell-class-name="table-header-row" empty-text="没有数据">
            <el-table-column label="月份" width="80" fixed>
              <template #default="scope">
                <div>{{ scope.row.serialNumber }}月</div>
              </template>
            </el-table-column>
            <el-table-column prop="late" label="迟到" width="80" fixed />
            <el-table-column prop="earlyLeave" label="早退" width="80" fixed />
            <el-table-column prop="absentCard" label="旷卡" width="80" fixed />
            <el-table-column prop="absentWork" label="旷工(天)" width="80" fixed />
            <el-table-column v-for="item in tebleColumnsHeader" :prop="`Category${item.dictValue}`" :label="item.dictLabel" width="80" />
            <el-table-column />
            <el-table-column prop="remark" label="备注" width="120" />
          </el-table>
        </div>
        <div class="teble-2" ref="teble2">
          <div class="table-title">{{ currentMonth.getFullYear() }}年请假情况汇总</div>
          <el-table :data="tableData2" v-loading="loading" scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
            <el-table-column label="月份" width="80" fixed>
              <template #default="scope">
                <div>{{ scope.row.serialNumber }}月</div>
              </template>
            </el-table-column>
            <el-table-column prop="late" label="迟到" width="80" fixed />
            <el-table-column prop="earlyLeave" label="早退" width="80" fixed />
            <el-table-column prop="absentCard" label="旷卡" width="80" fixed />
            <el-table-column prop="absentWork" label="旷工(天)" width="80" fixed />
            <el-table-column v-for="item in tebleColumnsHeader" :prop="`Category${item.dictValue}`" :label="`${item.dictLabel}`" width="80" />
            <el-table-column />
            <el-table-column prop="total" label="总计" width="120" />
          </el-table>
        </div>
      </div>
    </template>
  </ContainerLayoutV2>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, nextTick } from 'vue'
import ContainerLayoutV2 from '../layout/ContainerLayoutV2.vue'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import { useHolidayCategoryStore, useUsersStore, useDeptStore } from '../stores'
import { formatDate } from '../utils'
import { Refresh, Search } from '@element-plus/icons-vue'
import api from '../api'

const containerLayoutRef = ref<InstanceType<typeof ContainerLayoutV2> | null>(null)
// 请假类型
const holidayCategoryList = useHolidayCategoryStore().getAllState()
// const usersList = useUsersStore().userAllList
const loading = ref(false)
const teble2 = ref()
const tableHeight = ref(500)
const tableData = ref<any[]>([])
const tableData1 = ref<any[]>([])
const tableData2 = ref<any[]>([])
const leaveList = ref<any[]>([])
const currentMonth = ref(new Date())
const tebleColumnsHeader = ref<any[]>([])
// 表单
const queryForm = reactive({
  user: '',
  projectId: '',
  date: new Date(),
  deptIds: [] as string[] | number[],
})

onMounted(async () => {
  // 初始化部门ID
  await initDepIds()

  // 设置表格高度
  await setTableHeight()

  // 按假期类型设置表头
  await setTableColumnsHeader()
})

/**
 * 初始化部门ID
 */
const initDepIds = () => {
  const list = useDeptStore().getAllListState()
  const item = list.find((res: any) => res.deptId === useUsersStore().user.deptId)

  const deptIds = item.ancestors.split(',').map(Number).slice(1).concat(item.deptId)
  queryForm.deptIds = deptIds
}

/**
 * 设置表格高度
 *
 * 如果存在表格容器，则获取该容器的高度并赋值给表格高度变量
 */
const setTableHeight = () => {
  if (teble2.value) {
    nextTick(() => {
      tableHeight.value = teble2.value.offsetHeight - 48
    })
  }
}

/**
 * 设置表格列头
 *
 * 该函数用于设置表格的列头数据。
 */
const setTableColumnsHeader = () => {
  tebleColumnsHeader.value = holidayCategoryList.map((item) => {
    return {
      dictValue: item.dictValue,
      dictLabel: item.dictLabel,
    }
  })
}
/**
 * 获取用户请假信息列表的异步函数(全年，通过状态)
 *
 * @returns 无返回值
 */
const getLeaveList = async () => {
  currentMonth.value = new Date(queryForm.date)
  const start = new Date(currentMonth.value!.getFullYear(), 0, 1)
  const end = new Date(currentMonth.value!.getFullYear(), 11, 31)
  const params = {
    userName: queryForm.user,
    pageSize: 99999,
    startLeaveDate: formatDate(start, 'yyyy-MM-dd'),
    endLeaveDate: formatDate(end, 'yyyy-MM-dd'),
    leaveStatus: 3,
  }
  leaveList.value = await api.Leave.getList(params)
}
/**
 * 获取用户每个休假的使用和剩余
 * @param userName 用户名
 * @param deptId 部门ID
 * @param yearNum 年份
 * @returns 用户请假记录列表
 */
const getUserLeaveList = async (deptId: any) => {
  const params = {
    userName: queryForm.user,
    deptId,
    yearNum: currentMonth.value!.getFullYear(),
  }
  const rows = await api.Holiday.getSearch(params)
  console.log('rows', rows)
  return rows.map((e: any) => {
    const { holidayUsedNum, holidayCategory, userId } = e
    return { holidayUsedNum, holidayCategory, userId }
  })
}
/**
 * 聚合数据
 *
 * 该函数用于处理请假列表数据，根据当前月份聚合请假信息和请假类型。
 */
const dataAggregation = async (deptId: any) => {
  getUserLeaveList(deptId)
  // 获取当前月份的请假列表
  // const currentMonthLeaveList = leaveList.value.filter((item) => {
  //   const leaveDate = new Date(item.leaveDate)
  //   return leaveDate.getMonth() === currentMonth.value!.getMonth()
  // })

  // 用户每个休假的使用和剩余
  // const userLeaveList = await getUserLeaveList(deptId)
  // console.log('userLeaveList', userLeaveList)
  // 用户
  // const users = usersList.filter((item) => item.deptId === deptId)

  console.log('leaveList.value', leaveList.value)

  tableData.value = [
    {
      serialNumber: 1,
      department: 'HR',
      name: 'Alice',
      late: 1,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 1,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 5,
      sickLeaveYearly: 2,
      annualLeaveYearly: 10,
      compensatoryLeaveYearly: 3,
      marriageLeaveYearly: 1,
      funeralLeaveYearly: 0,
      total: 6,
    },
    {
      serialNumber: 2,
      department: 'IT',
      name: 'Bob',
      late: 0,
      earlyLeave: 1,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 1,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 3,
      sickLeaveYearly: 4,
      annualLeaveYearly: 8,
      compensatoryLeaveYearly: 2,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 1,
      total: 5,
    },
    {
      serialNumber: 3,
      department: 'Finance',
      name: 'Charlie',
      late: 0,
      earlyLeave: 0,
      absentCard: 1,
      absentWork: 0,
      Category0: 1,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 2,
      sickLeaveYearly: 1,
      annualLeaveYearly: 12,
      compensatoryLeaveYearly: 1,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 4,
    },
    {
      serialNumber: 4,
      department: 'Marketing',
      name: 'David',
      late: 1,
      earlyLeave: 1,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 1,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 4,
      sickLeaveYearly: 3,
      annualLeaveYearly: 7,
      compensatoryLeaveYearly: 4,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 5,
    },
    {
      serialNumber: 5,
      department: 'Sales',
      name: 'Eve',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 1,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 1,
      sickLeaveYearly: 0,
      annualLeaveYearly: 5,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 1,
      funeralLeaveYearly: 0,
      total: 1,
    },
    {
      serialNumber: 6,
      department: 'Operations',
      name: 'Frank',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 1,
      Category7: 1,
      Category8: 1,
      Category9: 1,
      Category10: 1,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 1,
      annualLeaveYearly: 3,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 1,
      total: 1,
    },
    {
      serialNumber: 7,
      department: 'HR',
      name: 'Grace',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 1,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 0,
      annualLeaveYearly: 0,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 1,
    },
    {
      serialNumber: 8,
      department: 'IT',
      name: 'Hank',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 0,
      annualLeaveYearly: 0,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 0,
    },
    {
      serialNumber: 9,
      department: 'Finance',
      name: 'Ivy',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 0,
      annualLeaveYearly: 0,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 0,
    },
    {
      serialNumber: 10,
      department: 'Marketing',
      name: 'Jack',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 0,
      annualLeaveYearly: 0,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 0,
    },
    {
      serialNumber: 11,
      department: 'Sales',
      name: 'Karen',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 0,
      annualLeaveYearly: 0,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 0,
    },
    {
      serialNumber: 12,
      department: 'Operations',
      name: 'Leo',
      late: 0,
      earlyLeave: 0,
      absentCard: 0,
      absentWork: 0,
      Category0: 0,
      Category1: 0,
      Category2: 0,
      Category3: 0,
      Category4: 0,
      Category5: 0,
      Category6: 0,
      Category7: 0,
      Category8: 0,
      Category9: 0,
      Category10: 0,
      remark: 'No remarks',
      personalLeaveYearly: 0,
      sickLeaveYearly: 0,
      annualLeaveYearly: 0,
      compensatoryLeaveYearly: 0,
      marriageLeaveYearly: 0,
      funeralLeaveYearly: 0,
      total: 0,
    },
  ]
  tableData1.value = [tableData.value[currentMonth.value.getMonth()]]
  tableData2.value = []
  await setTableHeight()
  tableData2.value = tableData.value
}

/**
 * 处理点击提交按钮的事件
 *
 * @returns 无返回值
 */
const handleClickBtnSubmit = async () => {
  const deptId = Object.assign([], queryForm.deptIds).pop()
  queryForm.user = (useUsersStore().user as any).userName

  // 获取用户请假信息列表的异步函数(全年，通过状态)
  await getLeaveList()

  // 数据聚合  
  await dataAggregation(deptId)
}

const handleClickBtnReset = () => {
  queryForm.user = ''
  queryForm.date = new Date()
  initDepIds()
  handleClickBtnSubmit()
}
</script>
<style scoped lang="scss">
.table-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .teble-2 {
    margin-top: 10px;
    flex: 1;
  }
}
</style>
